<template>
  <div>
    <van-tabbar route fixed>
      <van-tabbar-item icon="arrow-left"> 上一首 </van-tabbar-item>
      <van-tabbar-item
        v-show="playerState != 1"
        @click="changePlayerState({ playerState: 1 })"
        icon="play-circle-o"
      >
        播放
      </van-tabbar-item>

      <van-tabbar-item
        v-show="playerState == 1"
        @click="changePlayerState({ playerState: 2 })"
        icon="pause-circle-o"
      >
        暂停
      </van-tabbar-item>

      <van-tabbar-item icon="arrow"> 下一首 </van-tabbar-item>
    </van-tabbar>
    <audio ref="audio" :src="song.m4aUrl" @ended="urlsShift" @timeupdate="timeUpdate"></audio>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {};
  },
  computed: {
    ...mapState({
      isShowPlayer: "isShowPlayer",
      playerState: "playerState",
      songs: "songs",
      songsHistory: "songsHistory",
    }),
    audio() {
      return this.$refs.audio;
    },
    song() {
      if (this.songs.length > 0) return this.songs[0];
      else return { m4aUrl: "" };
    },
  },
  methods: {
    ...mapMutations([
      "changeShowPlayer",
      "changePlayerState",
      "deleteSongs",
      "addSongsHistory",
      "changePlayNowTime",
    ]),
    sleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    },
    async play() {
      //debugger;
      let state = 0;
      let count = 0;
      while (state != 4) {
        //2秒后还不行直接跳出
        await this.sleep(1000).then(() => {
          state = this.audio.readyState;
          count++;
        });
        if (count == 2) {
          break;
        }
      }
      if (this.audio.readyState == 4) {
        //加载完毕
        this.audio.play();
      } else {
        alert("网络故障，无法加载音乐,自动播放下一跳数据");
        console.log("无法加载音乐", this.audio.src);
        console.log("无法加载音乐", this.songs);
        this.urlsShift();
      }
    },
    pause() {
      this.audio.pause();
    },
    urlsShift() {
      //播放完毕需要删除第一条数据
      console.log("播放完毕");
      //debugger
      if (this.songs.length == 1) {
        return;
      } else {
        this.deleteSongs();
        this.$router.push({ path: "/SongDetail?id=" + this.song.songmid });
      }
    },
    timeUpdate(){
        let now =parseInt(this.$refs.audio.currentTime) ;
      this.changePlayNowTime({playNowTime:now})
    }
  },
  watch: {
    song: {
      handler(newValue, oldValue) {
        this.audio.load();
        this.play();
        //this.musicUrlsHistory.push(newValue);
        //this.addSongsHistory({song:newValue});
      },
    },
    playerState: {
      handler(newValue, oldValue) {
        if (newValue == 1) {
          this.play();
        } else if (newValue == 2) {
          this.pause();
        }
      },
    },
  },
};
</script>

<style>
</style>